package easy.demo11;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: wfmiss
 * @Date: 2023/12/24/19:51
 * @Description: 题目来源：力扣 https://leetcode.cn/problems/add-binary/
 * 67. 二进制求和
 * 给你两个二进制字符串 a 和 b ，以二进制字符串的形式返回它们的和。
 */
public class Solution {

    public static void main(String[] args) {
        /**
         * 测试用例：
         * 示例 1：
         * 输入:a = "11", b = "1"
         * 输出："100"
         *
         * 示例 2：
         * 输入：a = "1010", b = "1011"
         * 输出："10101"
         */
        System.out.println(addBinary("1010", "1011"));
    }

    /*
    * a+b+carry
    * 0+0+0 144 carry=0 result=0
    * 1+0+0 145 carry=0 result=1
    * 1+1+0 146 carry=1 result=0
    * 1+1+1 147 carry=1 result=1
    * */
    public static String addBinary(String a, String b) {
        int lengthA = a.length()-1;
        int lengthB = b.length()-1;
        char carry='0';
        String str="";
        while (lengthA>=0&&lengthB>=0){
            switch ((int)a.charAt(lengthA--)+b.charAt(lengthB--)+carry){
                case 144:
                    str+='0';
                    carry='0';
                    break;
                case 145:
                    str+='1';
                    carry='0';
                    break;
                case 146:
                    str+='0';
                    carry='1';
                    break;
                case 147:
                    str+='1';
                    carry='1';
                    break;
            }
        }
        /**
         * 0+0 96 carry=0 result=0
         * 1+0 97 carry=0 result=1
         * 1+1 98 carry=1 result=0
         */
        while (lengthA>=0){
            switch ((int)a.charAt(lengthA--)+carry){
                case 96:
                    str+='0';
                    carry='0';
                    break;
                case 97:
                    str+='1';
                    carry='0';
                    break;
                case 98:
                    str+='0';
                    carry='1';
                    break;
            }
        }
        while (lengthB>=0){
            switch ((int)b.charAt(lengthB--)+carry){
                case 96:
                    str+='0';
                    carry='0';
                    break;
                case 97:
                    str+='1';
                    carry='0';
                    break;
                case 98:
                    str+='0';
                    carry='1';
                    break;
            }
        }
        if (carry=='1') str+='1';
        str=new StringBuffer(str).reverse().toString();
        return str;
    }
}
